package com.hmdp.utils;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 批量为数据库中id=1~100的用户生成token并写入文件
 * 用于JMeter压测多用户发起请求时使用
 * 注：这里用到了spring的bean，需要在项目启动加载完成之后才能调用，也就是说需要在测试类中加上@SpringBootTest使用
 */
@Component
public class TokenGenerator {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserServiceImpl userService;

    // 用户id范围
    private static final int START_ID = 1;
    private static final int END_ID = 100;

    // token保存路径：当前项目类路径下
    private static final String TOKEN_FILE_PATH =
            System.getProperty("user.dir") + "/src/main/resources/tokens.txt";

    public void generateTokens(int startId, int endId) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(TOKEN_FILE_PATH))) {
            for (long id = startId; id <= endId; id++) {
                // 1. 查询用户
                User user = userService.getById(id);
                if (user == null) {
                    System.err.println("⚠️ 用户id=" + id + " 不存在，已跳过");
                    continue;
                }

                // 2. 转换为UserDTO
                UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

                // 3. 生成token
                String token = UUID.randomUUID().toString(true);
                String tokenKey = RedisConstants.LOGIN_USER_KEY + token;

                // 4. 转为Map并写入Redis
                Map<String, Object> userMap = BeanUtil.beanToMap(
                        userDTO, new HashMap<>(),
                        CopyOptions.create()
                                .ignoreNullValue()
                                .setFieldValueEditor((name, value) -> value.toString())
                );

                stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
                stringRedisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);

                // 5. 将token写入文件
                writer.write(token);
                writer.newLine();
            }
        }

        System.out.println("✅ 成功为id=" + startId + " ~ " + endId + " 的用户生成token，保存至：" + TOKEN_FILE_PATH);
    }
}
